<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 标题 -->
      <div class="login-header">
        <h1 class="title">后台管理系统</h1>
        <p class="subtitle">Admin Nexus Management System</p>
      </div>

      <!-- 登录表单 -->
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        size="large"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item prop="captchaCode">
          <div class="captcha-row">
            <el-input
              v-model="loginForm.captchaCode"
              placeholder="请输入验证码"
              prefix-icon="Key"
              clearable
              @keyup.enter="handleLogin"
            />
            <img
              v-if="captchaImage"
              :src="captchaImage"
              class="captcha-image"
              alt="验证码"
              @click="loadCaptcha"
            />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="loading" class="login-button" @click="handleLogin">
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 主题切换 -->
      <div class="theme-toggle-wrapper">
        <theme-toggle />
      </div>
    </div>

    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="circle circle-1"></div>
      <div class="circle circle-2"></div>
      <div class="circle circle-3"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  getCaptcha,
  getUserInfo,
  getUserMenus,
  getUserPermissions,
  login
} from '@/api/system/user.api'
import ThemeToggle from '@/components/ThemeToggle.vue'
import { usePermissionStore } from '@/stores/permission'
import { useUserStore } from '@/stores/user'
import { setToken } from '@/utils/auth'
import { to } from '@/utils/promise'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const permissionStore = usePermissionStore()

const loginFormRef = ref<FormInstance>()
const loading = ref(false)
const captchaImage = ref('')
const captchaId = ref('')

// 登录表单
const loginForm = reactive({
  username: '',
  password: '',
  captchaId: '',
  captchaCode: ''
})

// 表单验证规则
const loginRules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  captchaCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

/**
 * 加载验证码
 */
const loadCaptcha = async () => {
  const [error, response] = await to(getCaptcha())
  if (error) {
    ElMessage.error('获取验证码失败')
    return
  }
  captchaId.value = response.captchaId
  captchaImage.value = response.captchaImage
  loginForm.captchaId = response.captchaId
}

/**
 * 处理登录
 */
const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (!valid) return

    loading.value = true

    try {
      // 1. 登录获取 token
      const loginRes = await login(loginForm)
      const { token } = loginRes

      // 2. 保存 token
      setToken(token)
      userStore.setToken(token)

      // 3. 获取用户信息
      const userInfo = await getUserInfo()
      userStore.setUserInfo(userInfo)

      // 4. 获取用户菜单
      const menus = await getUserMenus()
      console.log('menus', menus)
      userStore.setMenuList(menus)

      // 5. 获取用户权限
      const permissions = await getUserPermissions()
      userStore.setPermissions(permissions)

      // 6. 生成动态路由
      await permissionStore.generateRoutes()

      ElMessage.success('登录成功')

      // 7. 跳转到目标页面
      router.push({ name: 'Home' })
    } catch (error: any) {
      console.error('登录失败:', error)
      ElMessage.error(error.message || '登录失败，请检查用户名和密码')
      // 登录失败后刷新验证码
      loadCaptcha()
      loginForm.captchaCode = ''
    } finally {
      loading.value = false
    }
  })
}

// 组件挂载时加载验证码
onMounted(() => {
  loadCaptcha()
})
</script>

<style scoped lang="scss">
.login-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

  .dark & {
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
  }
}

.login-box {
  position: relative;
  z-index: 10;
  width: 420px;
  padding: 48px 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);

  .dark & {
    background: rgba(30, 30, 30, 0.95);
  }
}

.login-header {
  margin-bottom: 40px;
  text-align: center;

  .title {
    margin: 0 0 8px;
    font-size: 28px;
    font-weight: bold;
    color: #333;

    .dark & {
      color: #fff;
    }
  }

  .subtitle {
    margin: 0;
    font-size: 14px;
    color: #999;

    .dark & {
      color: #666;
    }
  }
}

.login-form {
  .captcha-row {
    display: flex;
    gap: 12px;
    align-items: center;

    .el-input {
      flex: 1;
    }

    .captcha-image {
      width: 120px;
      height: 40px;
      border-radius: 4px;
      cursor: pointer;
      transition: opacity 0.3s;

      &:hover {
        opacity: 0.8;
      }
    }
  }

  .login-button {
    width: 100%;
    margin-top: 12px;
    font-size: 16px;
    font-weight: 500;
  }
}

.theme-toggle-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  position: absolute;
  right: 2rem;
  top: 0;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  pointer-events: none;

  .circle {
    position: absolute;
    border-radius: 50%;
    background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
    animation: float 20s infinite ease-in-out;

    &.circle-1 {
      top: 10%;
      left: 10%;
      width: 300px;
      height: 300px;
      animation-delay: 0s;
    }

    &.circle-2 {
      top: 60%;
      right: 10%;
      width: 400px;
      height: 400px;
      animation-delay: 5s;
    }

    &.circle-3 {
      bottom: 10%;
      left: 50%;
      width: 250px;
      height: 250px;
      animation-delay: 10s;
    }
  }
}

@keyframes float {
  0%,
  100% {
    transform: translate(0, 0) scale(1);
  }
  33% {
    transform: translate(30px, -30px) scale(1.1);
  }
  66% {
    transform: translate(-20px, 20px) scale(0.9);
  }
}
</style>
